using System.Net.Http.Json;
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using JsonClient.Models;

namespace JsonClient;

[ObservableObject]
public partial class MainPageViewModel {
    [ObservableProperty] private string _result;

    private HttpClient _httpClient = new();

    [RelayCommand]
    private async Task GetWithoutParameter() {
        var response =
            await _httpClient.GetAsync(
                "http://localhost:5190/Demo/getWithoutParameter");
        var json = await response.Content.ReadAsStringAsync();
        Result = json;

        var model = JsonSerializer.Deserialize<DemoModel>(json);
        // ...
    }

    [RelayCommand]
    private async Task GetWithParameter() {
        var response = await _httpClient.GetAsync(
            "http://localhost:5190/Demo/getWithParameter?id=2&name=name2");
        var json = await response.Content.ReadAsStringAsync();
        Result = json;

        var model = JsonSerializer.Deserialize<DemoModel>(json);
        // ...
    }

    [RelayCommand]
    private async Task Post() {
        var modelToPost = new DemoModel { Id = 3, Name = "Name 3" };
        var content = JsonContent.Create(modelToPost);

        var response = await _httpClient.PostAsync(
            "http://localhost:5190/Demo/post", content);
        var json = await response.Content.ReadAsStringAsync();
        Result = json;

        var model = JsonSerializer.Deserialize<DemoModel>(json);
        // ...
    }

    [RelayCommand]
    private async Task Put() {
        var modelToPut = new DemoModel { Id = 4, Name = "Name 4" };
        var content = JsonContent.Create(modelToPut);

        var response = await _httpClient.PutAsync(
            "http://localhost:5190/Demo/put", content);
        var json = await response.Content.ReadAsStringAsync();
        Result = json;

        var model = JsonSerializer.Deserialize<DemoModel>(json);
        // ...
    }
    
    [RelayCommand]
    private async Task Delete() {
        var response = await _httpClient.DeleteAsync(
            "http://localhost:5190/Demo/delete?id=5");
        var json = await response.Content.ReadAsStringAsync();
        Result = json;

        var model = JsonSerializer.Deserialize<DemoModel>(json);
        // ...
    }
}